package example4;

import org.junit.Test;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class ObjectInputOutputTest {

    @Test
    public void write() {
        ObjectOutputStream objectOutputStream = null;
        try {
            FileOutputStream fileOutputStream = new FileOutputStream("1.dat");
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            User user1 = new User(1,"赵丽颖");
            User user2 = new User(2,"刘涛");
            objectOutputStream.writeObject(user1);
            objectOutputStream.flush();
            objectOutputStream.writeObject(user2);
            objectOutputStream.flush();
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }





    @Test
    public void read() {
        ObjectInputStream objectInputStream = null;
        try {
            FileInputStream fileInputStream = new FileInputStream("1.dat");
            objectInputStream = new ObjectInputStream(fileInputStream);

            User user1 = (User) objectInputStream.readObject();
            System.out.println(user1);

            User user2 = (User) objectInputStream.readObject();
            System.out.println(user2);
        }
        catch (Exception e) {
            e.printStackTrace();
        }
        finally {
            if (objectInputStream != null) {
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}





class User implements Serializable {
    //序列化标识 标识同一个对象
    private static final long serialVersionUID = -891564516561L;

    private Integer id;
    private String name;

    //不能序列化
    private transient String lastName;
    //不能序列化
    private static Integer age;

    public User() {
    }

    public User(Integer id, String name) {
        this.id = id;
        this.name = name;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "User{" +
                "id=" + id +
                ", name='" + name + '\'' +
                '}';
    }


}


